#include <iostream>

#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;
using namespace cv::ml;

int main(int argc, char **argv)
{
    Mat NumData, NumLabels;
    int trainNum = 4;
    // 红桃-*_0 黑桃-*_1 方片-*_2 梅花-*_3 大王-4 小王-5 万能-6
    string NumName[] = {"1_", "2_", "3_", "4_", "5_", "6_", "7_", "8_", "9_", "10_", "j_", "q_", "k_"};
    for (int num = 0; num < 10; num++) {
        for (int i = 0; i < trainNum * 13; i++) {
            Mat img, tmp;
            string path = "data/";
            path.append(NumName[i / trainNum]).append(to_string((i % trainNum))).append(".png");
            img = imread(path);
            resize(img, tmp, cv::Size(70, 96));
            NumData.push_back(tmp.reshape(1, 1)); // 序列化
            NumLabels.push_back((i / trainNum + 1) << 4 | (i % trainNum)); // 标注
        }

        Mat img, tmp;
        string path = "data/";
        img = imread(path + "0.png");
        resize(img, tmp, cv::Size(70, 96));
        NumData.push_back(tmp.reshape(1, 1)); // 序列化
        NumLabels.push_back(5); // 标注
        img = imread(path + "1.png");
        resize(img, tmp, cv::Size(70, 96));
        NumData.push_back(tmp.reshape(1, 1)); // 序列化
        NumLabels.push_back(4); // 标注
    }

    NumData.convertTo(NumData, CV_32F);
    // 使用KNN算法
    int K = 3;
    Ptr<TrainData> tData = TrainData::create(NumData, ROW_SAMPLE, NumLabels);
    Ptr<KNearest> NumModel = KNearest::create();
    NumModel->setDefaultK(K);
    NumModel->setIsClassifier(true);
    NumModel->train(tData);
    NumModel->save("./knn_pixel.yml");
    return 0;
}